
var Dismantlement = function() {


    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var detail_url = $('.detail_url').val();
    var redirect_url = $('.redirect_url').val();
    var contentData_url = $('.contentData_url').val();

    // 七牛
    var upload_element = 'cover-image'; // 上传按钮的上级元素ID
    var upload_btn = 'upload-cover-btn'; // 上传按钮的ID
    var field = $('#' + upload_btn).attr('data-field');
    var token_url = $('.token_url').val();
    var record_url = $('.record_url').val();
    var max_file_size = $('#' + upload_btn).attr('data-max_file_size');
    var extensions = $('#' + upload_btn).attr('data-extensions');
    var multi = $('#' + upload_btn).attr('data-multi');
    var init_datepicker = function () {
        if($('.reportDate').length > 0){
            $('.reportDate').datepicker({
                language:"cn",
                format: 'yyyy-mm-dd',
                todayBtn : "linked",
                autoclose : true,
                todayHighlight : true,
                startDate : new Date()
            });
        }
        if($('.reportDate_time').length > 0){
            $('.reportDate_time').timepicker({
                //defaultTime: false,
                autoclose: true,
                showMeridian: false, // 24小时模式
                showSeconds: false, // 显示秒字段
                minuteStep: 5, // 指定分钟字段的步骤
                /*icons: {
                    up: 'glyphicon glyphicon-chevron-up',
                    down: 'glyphicon glyphicon-chevron-down'
                }*/
            }).on('changeTime.timepicker',function(e){
                var time = e.time;
                var endTime = e.time.value;
                //var endTime = (time.hours + 1) + ':' + time.minutes + ':' + time.seconds;
                //$('#endTime').timepicker('setTime', endTime);
            });
        }

    };

    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {"data": "households"},
                    {
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<a href="'+data+'" target="_blank"><img src="'+data+'" style="width: 40px;height: 40px;"/></a>';
                        }
                    },
                    {"data": "address"},
                    /*{"data": "reportDate"},*/
                    {
                        "width": "20%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html ='';
                            html += '<a href="'+contentData_url+'?disId='+row.id+'" type="button" class="btn btn-info">汇报</a>';
                            html += '<a href="'+edit_url+'?id='+row.id+'" type="button" class="btn btn-success">编辑</a>';
                            html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": false,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "order": [
                    [0, "desc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 1, 2, 3]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });

            // 筛选
            $('#doSearch').on('click', function(event){
                var param = $('#searchForm').serializeObject();

                tableSearch(table, param);
            });

            // 删除
            table.on('click', '.delete-btn', function(event) {
                // 操作行对象
                var dataArr = table.DataTable().rows($(this).parents("tr")).data();
                var id = dataArr[0].id;
                var _this = $(this);

                var text = '是否要删除这条数据？';
                var title = '请确认';
                var confirmBtn = '确定';
                var cancelBtn = '取消';
                event.preventDefault();

                layer.confirm(
                    text,
                    {
                        title: title,
                        btn: [confirmBtn, cancelBtn]
                    },
                    function(index){
                        layer.close(index);
                        var url = delete_url;
                        var data = {'id':id};
                        layer.load(2, {shade: [0.8,'#000000']}); // 打开loading

                        $.ajax({
                            url: url,
                            type: 'POST',
                            data: data,
                            dataType : 'json',
                            success: function (data) {
                                layer.closeAll('loading'); // 关闭loading
                                layer.msg(data.msg);
                                if(data.code == 1){
                                    _this.parents('tr').remove();
                                }
                            }
                        });
                    }
                );
            });
        } else {
            // 百度地图API功能
            //创建Map实例
            var map = new BMap.Map("map_container");
            //初始化武汉坐标
            var point = new BMap.Point(114.405492,30.502934);
            var offsetY = 200;
            //地图平移缩放控件：默认左上方
            map.addControl(new BMap.NavigationControl());
            //比例尺控件，默认位于地图左下方，显示地图的比例关系
            map.addControl(new BMap.ScaleControl());
            map.centerAndZoom(point,12);
            //添加鼠标滚动缩放
            map.enableScrollWheelZoom(true);
            //设置标注的图标

            //显示地址信息窗口
            var marker = new BMap.Marker(point);
            //把标注添加到地图上
            map.addOverlay(marker);

            //地址解析类
            var gc = new BMap.Geocoder();
            function showLocationInfo(pt, rs){
                var addComp = rs.addressComponents;
                $("#longitude").val(pt.lng);
                $("#latitude").val(pt.lat);
                console.log('经纬度：'+pt.lat+' '+pt.lng);
                $("#add-text1").val(pt.lat+','+pt.lng);
            }

            //删除标注
            function deletePoint(){
                var allOverlay = map.getOverlays();
                for (var i = 0; i < allOverlay.length; i++){
                    map.removeOverlay(allOverlay[i]);
                }
            }

            //根据选择框或输入框获取地址
            var _area={
                //keyword:'',
                _address:$("#address"),
                unChecked:function(val){
                    return (val==''||typeof (val)=='undefined'||val==null||
                        val=='省份'||val=='地级市'||val=='市、县级市')?false:true;
                },
                list:function(){
                    var _joinArea='';
                    if(_area.unChecked(this._address.val())){
                        _joinArea+=' '+this._address.val();
                        //_joinArea=this._address.val();
                    }
                    return _joinArea;
                },
                init:function(){
                    //绑定百度地图
                    var _this=_area.list();
                    //定义local
                    var local = new BMap.LocalSearch(map, {
                        renderOptions: {
                            map: map,
                            panel: "results",//结果容器id
                            autoViewport: true,   //自动结果标注
                            selectFirstResult: true  , //指定到第一个目标
                            enableRouteSearchBox: true,
                            enableRouteInfo:true
                        },
                        pageCapacity: 1
                    });

                    local.setSearchCompleteCallback(function (searchResult) {
                        var poi = searchResult.getPoi(0);
                        //document.getElementById("result_").value = poi.point.lng + "," + poi.point.lat;
                        map.centerAndZoom(poi.point, 12);
                        gc.getLocation(poi.point, function(rs){
                            showLocationInfo(poi.point, rs);
                        });
                    });
                    local.search(_this);
                }
            }

            //全局变量：存储address字符串长度做判断
            var _thisLength='';
            $("#address").keydown(function(){
                _thisLength=$(this).val().length;
            })
            $("#address").keyup(function(){
                var _newLength=$(this).val().length;
                var timer=setTimeout(function(){
                    if(_thisLength<=_newLength){
                        deletePoint();
                        _area.init();
                    }
                    else{
                        clearTimeout(timer);
                    }
                },1000);
            })
            $("#address").blur(function(){
                deletePoint();
                _area.init();
            })
        }
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    /**
     * 七牛初始化
     */
    var initUploader = function () {
        if($('#' + upload_element).length <= 0){
            return ;
        }

        var url = "";
        var qiniupercent = "";
        var uploader = upload_element;
        var pickfiles = upload_btn;
        if(max_file_size == '' || max_file_size == undefined){
            max_file_size = '1MB';
        }
        if(extensions == '' || extensions == undefined){
            extensions = 'jpg,jpeg,gif,png';
        }
        if(multi == 'false'){
            multi = false;
        }else{
            multi = true;
        }

        $.ajax({
            url: token_url,
            type: 'POST',
            data: {},
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            dataType : 'json',
            success: function (data) {
                uploaderReadyForImg(data.uptoken, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi);
            }
        });
    };

    var uploaderReadyForImg = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
        var uploaderForUditor = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: pickfiles,     //上传按钮的ID
            container: uploader,      //上传按钮的上级元素ID
            drop_element: uploader,
            max_file_size: max_file_size,         //最大文件限制
            flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
            dragdrop: false,
            chunk_size: '4mb',              //分块大小
            //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
            // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
            domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
            multi_selection: multi,         //是否允许同时选择多文件
            filters: {
                mime_types: [               //文件类型过滤，这里限制为图片类型
                    {title: "Image files", extensions: extensions}
                ]
            },
            auto_start: true,
            unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function(file) {
                        // 文件添加进队列后，处理相关的事情
                    });
                },
                'BeforeUpload': function (up, file) {
                    // 每个文件上传前，处理相关的事情
                    layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                },
                'UploadProgress': function (up, file) {
                    //文件上传时，处理相关的事情

                    //上传进度 class="layui-btn" type="button"

                    //console.log(file.percent + "%");
                },
                'UploadComplete': function () {
                    //do something
                },
                'FileUploaded': function (up, file, info) {
                    //每个文件上传成功后,处理相关的事情,并记录到数据库
                    //其中 info 是文件上传成功后，服务端返回的json，形式如
                    //{
                    //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                    //  "key": "gogopher.jpg"
                    //}
                    var domain = up.getOption('domain');
                    var res = eval('(' + info.response + ')');
                    var sourceLink = domain + res.key;//获取上传文件的链接地址
                    //console.log(sourceLink);
                    $.ajax({
                        url: record_url,
                        type: 'POST',
                        data: {
                            'imgUrl': sourceLink
                        },
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            //console.log(data);
                            layer.closeAll('loading'); // 关闭loading
                            if (data.code === '1') {
                                if(multi) {
                                    // 多图
                                    var $item = '';
                                    $item += '<span class="multi-image">';
                                    $item += '<input type="hidden" name="imgIds" value="'+data.image_id+'">';
                                    $item += '<input type="hidden" name="'+field+'" value="'+sourceLink+'">';
                                    $item += '<img class="exist-image" src="'+sourceLink+'" alt="" />';
                                    $item += '<img class="del" src="/public/static/pages/image/del.png" alt="">';
                                    $item += '</span>';

                                    $('#' + upload_btn).before($item);
                                } else {
                                    // 单图
                                    // 删除原图
                                    var img_id = $('#' + upload_btn).find('input[name=imgId]').val();
                                    var img_url = $('#' + upload_btn).find('img').attr('src');
                                    delOriginalImg(img_id, img_url);

                                    $('#' + upload_btn).find('img').attr('src', sourceLink);
                                    $('#' + upload_btn).find('input').val(sourceLink);
                                    $('#' + upload_btn).append('<input type="hidden" name="imgId" value="'+data.image_id+'">');
                                }
                                // imgcount++;
                            }
                        }
                    });

                },
                'Error': function (up, err, errTip) {
                    layer.closeAll('loading'); // 关闭loading
                    alert(errTip);
                },
            }
        });
    };

    // 删除原图
    var delOriginalImg = function (img_id, img_url) {
        var delimage_url = $('.delimage_url').val();

        $.ajax({
            url: delimage_url,
            type: 'POST',
            data: {
                'imgUrl' : img_url,
                'id' : img_id
            },
            cache: false,
            dataType : 'json',
            success: function (data) {
                //
            }
        });
    };


    return {
        init: function() {
            initTable();
            initUploader();
            init_datepicker();

            this.onEvent();
        },

        onEvent : function(){

            // 删除图片
            $(document).find('#cover-image').on('click', '.del', function(){
                var img_id = $(this).parent().find('input').val(); // 图片ID
                var img_url = $(this).parent().find('.exist-image').attr('src'); // 图片地址
                var element = $(this).parent(); // 要删除元素
                var delimage_url = $('.delimage_url').val();

                $.ajax({
                    url: delimage_url,
                    type: 'POST',
                    data: {
                        'imgUrl' : img_url,
                        'id' : img_id
                    },
                    cache: false,
                    dataType : 'json',
                    success: function (data) {
                        if(data.code === '1') {
                            element.remove();
                            layer.msg('删除成功');
                        } else{
                            layer.msg('删除失败');
                        }
                    }
                });
            });


            // 添加拆迁进度
            $('.addResume-btn').on('click', function(){
                var html = '';
                html += '<div class="resume-div">';
                html += '<div class="row" style="margin-top: 20px;">';
                html += '<div class="col-md-4">';
                html += '<input type="text" class="form-control reportDate" name="reportDate" value="" placeholder="请选择时间" autocomplete="off" readonly>';
                html += '</div>';
                html += '<div class="col-md-4">';
                html += '<input type="text" class="form-control reportDate_time" name="reportDate_time" value="" placeholder="请选择时间" autocomplete="off" readonly>';
                html += '</div>';
                html += '<div class="col-md-1">';
                html += '<button type="button" class="btn btn-danger remove-resume"><i class="fa fa-close"></i></button>';
                html += '</div>';
                html += '</div>';
                html += '<div class="row">';
                html += '<div class="col-md-12">';
                html += '<label class="control-label"></label>';
                html += '<textarea class="form-control" cols="80" rows="5" name="introduction" placeholder="请输入详情"></textarea>';
                html += '</div>';
                html += '</div>';
                html += '</div>';

                $('#resume-group').append(html);
                init_datepicker();
            });

            // 删除拆迁进度
            $(document).find('#resume-group').on('click', '.remove-resume', function(){
                $(this).parents('.resume-div').remove();
            });



            $('#form-submit').on('click', function () {
                var form = this.form;
                if(form.households.value.trim()=='') {
                    layer.msg('请输入拆迁户姓名');
                    form.name.focus();
                    return;
                }
                if(form.address.value.trim()=='') {
                    layer.msg('请输入地址');
                    form.address.focus();
                    return;
                }
                if(form.addressGeo.value.trim()==''){
                    layer.msg('没有获取到经纬度，请从所在市开始填写！');
                    form.address.focus();
                    return;
                }

                if($('#cover-image').find('img.exist-image').length <= 0){
                    layer.msg('请上图片');
                    return false;
                }
                var _data = $(form).serializeObject();
                $("#form-submit").attr("disabled","disabled");
                var posturl = $(form).attr('action');
                $.ajax({
                    url : posturl,
                    type : 'post',
                    dataType : 'json',
                    contentType : "application/json; charset=utf-8",
                    data : JSON.stringify(_data),
                }).done(function(data) {
                    if (data.code == 1) {
                        layer.msg('保存成功');
                        window.location.href= data.url; //加载页面数据
                    } else if (data.code === 0 ) {  // 错误
                        $("#form-submit").removeAttr("disabled");
                        layer.msg(data.msg);
                    }
                });

            });
        }
    };

}();


$(function() {
    Dismantlement.init();
    if($("#address").val() != ""){
        $("#address").blur();
    }

});
